import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.matrixzoo.common.entity;"
typeMapping = [
  (~/(?i)tinyint|smallint|int/)                      : "Integer",
  (~/(?i)float|double|decimal|real/): "Double",
  (~/(?i)date|datetime|timestamp|time/)                     : "Date",
  (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaClassName(table.getName(), true)
  def fields = calcFields(table)
  new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields,table) }
}

def generate(out, className, fields,table) {
  Set types = new HashSet()
  fields.each() {
    types.add(it.type)
  }

  out.println "package $packageName"
  out.println ""
  out.println "import com.matrixzoo.common.base.BaseEntity;"
  out.println "import io.swagger.annotations.ApiModel;"
  out.println "import io.swagger.annotations.ApiModelProperty;"

  if (types.contains("Date")) {
    out.println "import java.util.Date;"
  }
  out.println ""
  out.println "/**\n" +
          " * <p>Date: "+new java.util.Date().toString()+".</p>\n" +
          " *\n" +
          " * @author chenkai\n" +
          " */"
  out.println ""
  out.println "@ApiModel(value=\"" + className + "\", description=\"业务对象\")"
  out.println "public class $className extends BaseEntity implements Serializable {"
  out.println ""
  out.println genSerialID()
  out.println ""
  fields.each() {
    if (it.annos != "") out.println "  ${it.annos}"
    out.println "  private ${it.type} ${it.name};"
  }
  out.println ""
  fields.each() {
    out.println ""
    out.println "  public ${it.type} get${it.name.capitalize()}() {"
    out.println "    return ${it.name};"
    out.println "  }"
    out.println ""
    out.println "  public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
    out.println "    this.${it.name} = ${it.name};"
    out.println "  }"
    out.println ""
  }
  out.println "}"
}

def calcFields(table) {
  DasUtil.getColumns(table).reduce([]) { fields, col ->
    def spec = Case.LOWER.apply(col.getDataType().getSpecification())
    def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
    fields += [[
                 colName : col.getName(),
                 name : changeStyle (javaName(col.getName(), false) ,true),
                 type : typeStr,
                 commoent: col.getComment(),
                 annos: "@ApiModelProperty(\""+(isNotEmpty(col.getComment()) ? col.getComment(): col.getName())+"\")"]]
  }
}

def javaClassName(str, capitalize) {
  str = str.replaceAll("mz_", "")
  def s = str.split(/[^\p{Alnum}]/).collect { def s = Case.LOWER.apply(it).capitalize() }.join("")
  // 去除开头的T  http://developer.51cto.com/art/200906/129168.htm
//  s = s[1..s.size() - 3]
  capitalize ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

def javaName(str, capitalize) {
  def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
          .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

def isNotEmpty(content) {
  return content != null && content.toString().trim().length() > 0
}

static String changeStyle(String str, boolean toCamel){
  if(!str || str.size() <= 1)
    return str

  if(toCamel){
    String r = str.toLowerCase().split('_').collect{cc -> Case.LOWER.apply(cc).capitalize()}.join('')
    return r[0].toLowerCase() + r[1..-1]
  }else{
    str = str[0].toLowerCase() + str[1..-1]
    return str.collect{cc -> ((char)cc).isUpperCase() ? '_' + cc.toLowerCase() : cc}.join('')
  }
}

static String genSerialID()
{
  return "\tprivate static final long serialVersionUID =  "+Math.abs(new Random().nextLong())+"L;";
}